import React from 'react';
import { message } from 'antd';
import { Row, Col, Form, Modal, Input, Select, Radio, Switch, Button, Upload, Icon, Table } from 'antd';
import MapInputs from '../../../components/MapInputs';
import { DEFAULT_PAGE_SIZE } from '../../../utils/constants';
import { addKeyToDataSource } from '../../../utils';
import _ from 'lodash';
import styles from '../../common.css';
const FormItem = Form.Item;
const TextArea = Input.TextArea;
const Option = Select.Option;
const RadioGroup = Radio.Group;
const formItemLayout = {
  labelCol: {
    span: 6,
  },
  wrapperCol: {
    span: 17,
  },
};
const formItemLayout1 = {
  labelCol: {
    span: 3,
  },
  wrapperCol: {
    span: 20,
  },
};

@Form.create()
export default class TestReportModal extends React.Component {
  constructor(props) {
    super(props);
    this.state = {
      fileinfo: [],
      // relatejira: [], // 将查询出来的关联jira存下来，用于提交给后端保存
    };
  }
  handleOk = () => { // 点击OK时，执行修改or新增
    const { dispatch, currentUser, RelatedJira, form: { validateFields, getFieldsValue } } = this.props;
    validateFields((errors) => {
      if (errors) {
        return;
      }
      const test_case_path = this.state.fileinfo.length !== 0 ? JSON.stringify(this.state.fileinfo) : ''; // 上传的文件信息
      const jiraobj = currentUser.id ? [] : {
        bug_desc: RelatedJira.bug_desc ? (RelatedJira.bug_desc.length !== 0 ? JSON.stringify(RelatedJira.bug_desc) : '') : '',
        bug_details: RelatedJira.bug_obj ? (RelatedJira.bug_obj.length !== 0 ? JSON.stringify(RelatedJira.bug_obj) : '') : '',
        demand_detail: RelatedJira.demand_detail ? (RelatedJira.demand_detail.length !== 0 ? JSON.stringify(RelatedJira.demand_detail) : '') : '',
      };
      let adddata={
        // ...currentUser,
        ...getFieldsValue(),
        test_case_path,
        ...jiraobj,
      };
      let editdata={
        ...currentUser,
        ...getFieldsValue(),
      };
      const data = currentUser.id ? editdata : adddata;
      // data.test_case_path =JSON.stringify(data.test_case_path);
      // data.paramobj = JSON.stringify(data.paramobj);
      const type = `testreport/${data.id ? 'updateTestReport' : 'addTestReport'}`;// 根据是否有id
      dispatch({
        type,
        payload: {
          reportparam: data,
          cb: this.handleCancel,
        },
      });
    });
  };
  handleCancel = () => {
    const { dispatch, form: { resetFields }, onCancel } = this.props;
    resetFields();
    onCancel();
    dispatch({
      type: 'testreport/save',
      payload: {
        RelatedJira: [],
      },
    });
  };
  handleSearch = () => {
    const { dispatch, currentUser, form: { validateFields, getFieldsValue } } = this.props;
    const fields = ['project_name', 'fix_version']; // 对指定列进行校验
    validateFields(fields, (errors) => {
      if (errors) {
        return;
      }
      const data = {
        ...currentUser,
        ...getFieldsValue(fields),
      };
      const type = 'testreport/fetchRelatedJira';
      dispatch({
        type,
        payload: {
          params: data,
        },
      });
    });
  };
  handleSaveandSend = () => {
    const { dispatch, currentUser, RelatedJira, form: { validateFields, getFieldsValue } } = this.props;
    validateFields((errors) => {
      if (errors) {
        return;
      }
      const test_case_path= this.state.fileinfo.length !== 0 ? JSON.stringify(this.state.fileinfo) : ''; // 上传的文件信息
      const jiraobj = currentUser.id ? [] : {
        bug_desc: (RelatedJira.bug_desc.length !== 0) ? JSON.stringify(RelatedJira.bug_desc) : '',
        bug_details: (RelatedJira.bug_obj.length !== 0) ? JSON.stringify(RelatedJira.bug_obj) : '',
        demand_detail: (RelatedJira.demand_detail.length !== 0) ? JSON.stringify(RelatedJira.demand_detail) : '',
      };

      const adddata ={
        // ...currentUser,
        ...getFieldsValue(),
        test_case_path,
        ...jiraobj,
      };
      const editdata={
        ...currentUser,
        ...getFieldsValue(),
      };
      const data = currentUser.id ? editdata : adddata;
      const type = 'testreport/savesendTestReport';
      dispatch({
        type,
        payload: {
          reportparam: data,
          cb: this.handleCancel,
        },
      });
    });
  };
  handleDeleteAtta = (file_path) => {
    const { dispatch } = this.props;
    const type = 'testreport/deleteAttac';// 根据是否有id
    dispatch({
      type,
      payload: {
        param: file_path,
        cb: this.handleCancel,
      },
    });
  };
  handleDownloadAtta = () => {
    const { dispatch, currentUser } = this.props;
    const fileinfo = currentUser.test_case_path ? JSON.parse(currentUser.test_case_path) : '';
    const filepath = fileinfo ? fileinfo.file_path : '';
    if (filepath) {
      window.location.href = `api/downloadAtta/?file_path=${filepath}`;
    } else {
      message.warning('未上传附件，不可下载');
    }
  };
  render() {

    const { loading, visible, currentUser, ButtonVisible, testreportinfo, testreportinfoDetail, projectlist, RelatedJira, form: { getFieldDecorator } } = this.props;
    const modalProps = {
      title: currentUser.id ? '修改' : '新增', // 根据主键判断是否存在数据来决定走修改还是编辑，新增情况下，不会存在id，因为currentUser为空
      visible,
      // width: 780, //默认520
      wrapClassName: 'vertical-center-modal',
      confirmLoading: loading,
      maskClosable: false,
    };

    const UploadProps = {
      name: 'file',
      action: '/api/saveAttac/',
      headers: {
        authorization: 'authorization-text',
      },
      onChange: (info) => {
        if (info.file.status !== 'uploading') {
          console.log(info.file, info.fileList);
        }
        if (info.file.status === 'done') {
          message.success(`${info.file.name} file uploaded successfully`);
          // JSON.stringify(info.file.response.data)
          this.setState({
            fileinfo: info.file.response.data,
          });
        } else if (info.file.status === 'error') {
          message.error(`${info.file.name} file upload failed.`);
        }
      },
      onRemove: (info) => {
        // 删除单个附件
        const file_path = info.response.data.file_path;
        this.handleDeleteAtta(file_path);
        this.setState({ fileinfo: [] });
        // 删除多个附件
        // const deleteIndex = _.findIndex([this.state.fileinfo], item => {
        //   return item.file_name === file.name;
        // });
        //
        // if (deleteIndex !== -1) {
        //   uploadFilePath.splice(deleteIndex, 1);
        // }
        //
        // this.setState(({ fileList }) => {
        //   const index = fileList.indexOf(file);
        //   const newFileList = fileList.slice();
        //   newFileList.splice(index, 1);
        //   return {
        //     fileList: newFileList
        //   };
        // });
      },
    };
    const testColumns = [
      {
        title: '危险bug数',
        dataIndex: 'p0_bugnum',
        key: 'p0_bugnum',
      },
      {
        title: '严重/重要bug数',
        dataIndex: 'p1_bugnum',
        key: 'p1_bugnum',
      },
      {
        title: '轻微bug数',
        dataIndex: 'p2_bugnum',
        key: 'p2_bugnum',
      },
      {
        title: '总bug数',
        dataIndex: 'totalnum',
        key: 'totalnum',
      },
      {
        title: '遗留未解决bug数',
        dataIndex: 'remain_bugnum',
        key: 'remain_bugnum',
      },
    ];
    const jiraColumns = [
      {
        title: 'jiraID',
        dataIndex: 'jira_id',
        key: 'jiraID',
        width: '10%',
      },
      {
        title: '主题',
        dataIndex: 'summary',
        key: 'summary',
      },
      {
        title: '优先级',
        dataIndex: 'jira_priority',
        key: 'jira_priority',
        width: '15%',
      },
      {
        title: '解决方案',
        dataIndex: 'resolution',
        key: 'resolution',
        width: '15%',
      },
      {
        title: '经办人',
        dataIndex: 'assignee',
        key: 'assignee',
        width: '15%',
      },
    ];
    const statusType = [
      {
        id: '0',
        name: '未发布',
      },
      {
        id: '1',
        name: '通过',
      },
      {
        id: '2',
        name: '不通过',
      },
    ];

    const i = currentUser.id ? (currentUser.bug_desc.length !== 0 ? JSON.parse(currentUser.bug_desc) : []) : [];
    const arry_bug_desc = (i.length !== 0) ? [i] : [];

    const bugObj = currentUser.id ? (currentUser.bug_desc.length !== 0 ? addKeyToDataSource(arry_bug_desc) : []) : (RelatedJira['bug_desc'] ? addKeyToDataSource([RelatedJira['bug_desc']]) : []);
    return (
      <div>
          <Row>
            <div className={styles.btnGroup}>
              <Button type="primary" icon="left" onClick={this.handleCancel}>Go back</Button>
            </div>
          </Row>
        <Form>
          <Row gutter={24}>
            <Col span={8}>
              <FormItem
                label="报告名称"
                {...formItemLayout}
              >
                {getFieldDecorator('report_name', {
                  initialValue: currentUser.report_name || '',
                  rules: [
                    {
                      required: true,
                      message: '请输入报告名称',
                    },
                  ],
                })(
                  <Input/>
                )}
              </FormItem>
            </Col>
            <Col span={8}>
              <FormItem
                label="报告人"
                {...formItemLayout}
              >
                {getFieldDecorator('reporter', {
                  initialValue: currentUser.reporter || '',
                  rules: [
                    {
                      required: true,
                    },
                  ],
                })(
                  <Input/>
                )}
              </FormItem>
            </Col>
          </Row>
          <Row gutter={24}>
            <Col span={8}>
              <FormItem
                label="project_name"
                {...formItemLayout}
              >
                {getFieldDecorator('project_name', { // 此处写的参数需与接口参数key对应
                  initialValue: currentUser.project_name || '',
                  rules: [
                    {
                      required: true,
                      message: '请输入项目名称',
                    },
                  ],
                })(
                  <Select
                    showSearch
                    optionFilterProp="children"
                    disabled={ButtonVisible}
                    filterOption={(input, option) =>
                      option.props.children.toLowerCase().indexOf(input.toLowerCase()) >= 0}
                  >
                    <Option key={-1} value="">请选择项目名称</Option>
                    {
                      projectlist.map((item, index) => {
                        return (<Option key={index} value={item}>{item}</Option>);
                      })
                    }
                  </Select>
                )}
              </FormItem>
            </Col>
            <Col span={8}>
              <FormItem
                label="版本号"
                {...formItemLayout}
              >
                {getFieldDecorator('fix_version', {
                  initialValue: currentUser.fix_version || ' ',
                  rules: [
                    {
                      required: true,
                    },
                  ],
                })(
                  <Input disabled={ButtonVisible} />
                )}
              </FormItem>
            </Col>
            <Col span={8}>
              <Button
                  type="primary"
                  loading={loading}
                  onClick={this.handleSearch}
                  disabled={ButtonVisible}
                >
                  查询
                </Button>
            </Col>
          </Row>
          <Row gutter={24}>
            <Table
              columns={testColumns}
              dataSource={bugObj}
              loading={loading}
              title={() => '发现的BUG情况'}
              pagination={{
                pageSize: DEFAULT_PAGE_SIZE,
              }}
              bordered
            />
          </Row>
          <Row gutter={24}>
            <Table
              columns={jiraColumns}
              dataSource={currentUser.id ? (currentUser.bug_details.length !== 0 ? JSON.parse(currentUser.bug_details) : []) : RelatedJira['bug_obj']}
              loading={loading}
              rowKey={record => record.id}
              title={() => 'BUG详情'}
              pagination={{
                pageSize: DEFAULT_PAGE_SIZE,
              }}
              bordered
            />
          </Row>
          <Row gutter={24}>
            <Table
              columns={jiraColumns}
              dataSource={currentUser.id ? (currentUser.demand_detail.length !== 0 ? JSON.parse(currentUser.demand_detail) : []) : RelatedJira['demand_detail']}
              loading={loading}
              rowKey={record => record.id}
              title={() => '需求详情'}
              pagination={{
                pageSize: DEFAULT_PAGE_SIZE,
              }}
              bordered
            />
          </Row>
          <Row gutter={24}>
            <Col span={8}>
              <FormItem
                label="测试结果"
                {...formItemLayout}
              >
                {getFieldDecorator('status', {
                  initialValue: /\d+/.test(currentUser.status) ? `${currentUser.status}` : '',
                  rules: [{
                    required: true,
                  }],
                })(
                  <Select>
                    <Option key={-1} value="">请选择</Option>
                    {
                      statusType.map((item, index) => {
                        return (
                          <Option key={index} value={`${item.id}`}>{item.name}</Option>
                        );
                      })
                    }
                  </Select>
                )}
              </FormItem>
            </Col>
          </Row>
          <Row>
            <Col span={16}>
              <FormItem
                label="测试总结"
                {...formItemLayout1}
              >
                {getFieldDecorator('conclusion', {
                  initialValue: currentUser.conclusion || '',
                  rules: [{
                    required: true,
                  }],
                })(
                  <TextArea rows={4} />
                )}
              </FormItem>
            </Col>
          </Row>
          <Row>
            <Col span={16}>
              <FormItem
                label="风险"
                {...formItemLayout1}
              >
                {getFieldDecorator('risk', {
                  initialValue: currentUser.risk || '',
                })(
                  <TextArea rows={2} />
                )}
              </FormItem>
            </Col>
          </Row>
          <Row>
            <Col span={16}>
              <FormItem
                label="测试范围"
                {...formItemLayout1}
              >
                {getFieldDecorator('testcoverrate', {
                  initialValue: currentUser.testcoverrate || '',
                })(
                  <TextArea rows={2} />
                )}
              </FormItem>
            </Col>
          </Row>
          <Row>
            <Col span={16}>
              <FormItem
                label="测试标准"
                {...formItemLayout1}
              >
                {getFieldDecorator('criterion', {
                  initialValue: currentUser.criterion || '',
                })(
                  <TextArea />
                )}
              </FormItem>
            </Col>
          </Row>
          <Row>
            <Col span={16}>
              <FormItem
                label="测试环境"
                {...formItemLayout1}
              >
                {getFieldDecorator('environment', {
                  initialValue: currentUser.environment || '',
                })(
                  <TextArea />
                )}
              </FormItem>
            </Col>
          </Row>
          <Row>
            <Col span={16}>
              <FormItem
                label="测试策略"
                {...formItemLayout1}
              >
                {getFieldDecorator('strategy', {
                  initialValue: currentUser.strategy || '',
                })(
                  <TextArea />
                )}
              </FormItem>
            </Col>
          </Row>
          <Row>
            <Col span={16}>
              <FormItem
                label="遗留问题"
                {...formItemLayout1}
              >
                {getFieldDecorator('remain_question', {
                  initialValue: currentUser.remain_question || '',
                })(
                  <TextArea />
                )}
              </FormItem>
            </Col>
          </Row>
          <Row>
            <Col span={16}>
              <FormItem
                label="建议"
                {...formItemLayout1}
              >
                {getFieldDecorator('qa_suggestion', {
                  initialValue: currentUser.qa_suggestion || '',
                })(
                  <TextArea rows={4} />
                )}
              </FormItem>
            </Col>
          </Row>
          <Row>
            {
              currentUser.id ? (
                <Button  type="primary" icon="download" onClick={this.handleDownloadAtta}>
                  下载附件
                </Button>
              ) : (
                <FormItem
                  label="上传附件"
                  {...formItemLayout1}
                >
                  {getFieldDecorator('test_case_path')(
                    <Upload {...UploadProps} >
                      <Button>
                        <Icon type="upload" /> 选择文件
                      </Button>
                      <span
                        style={{
                          marginLeft: 16,
                          color: '#cccccc',
                        }}
                      >
                    支持所有扩展名
                  </span>
                    </Upload>
                  )}
                </FormItem>
              )
            }
          </Row>
          <Row gutter={12} style={{ marginBottom: 8 }}>
            <div className={styles.btnGroup} >
              <Button
                type="primary"
                // loading={loading}
                onClick={this.handleOk}
              >
                保存
              </Button>
              <Button type="primary" style={{ margin: 8 }} onClick={this.handleCancel}>取消</Button>
              <Button type="primary" onClick={this.handleSaveandSend}>保存并发送</Button>
            </div>
          </Row>
        </Form>
      </div>
    );
  }
}

